// import Qs from 'qs';
import axios from 'axios'
import { getToken, delToken } from '@/utils/auth';
import router from '@/router';
import { Message } from 'element-ui'
import { defaultURLPrefix, defaultTimeout } from '../settings'
import * as tr from "./tr";

// 创建一个 axios 实例
const instance = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL, // url = base url + request url
  timeout: defaultTimeout // 超时时间
})

// 添加头部信息
function addRequestHeaders(config, jwtToken) {
  // 重置url
  const urlPrefix = typeof config.prefix === "string" ? config.prefix : defaultURLPrefix;
  const suffix = `?X-TS=${+new Date()}&X-Random=${Math.random().toString().slice(-10)}`;
  // mac校验
  const requestbody = `${urlPrefix}${config.url}${suffix}${config.data && config.method !== 'GET' ? JSON.stringify(config.data) : ""}`;
  config.url = `${config.baseURL}${urlPrefix}${config.url}${suffix}`;

  if (config.method === "POST") {
    config.headers = {
      Accept: "application/json",
      "Content-Type": "application/json; charset=utf-8",
      ...config.headers
    };
  }
  // 添加请求头
  config.headers = {
    ...config.headers,
    credentials: "include",
    Authorization: jwtToken,
    Signature: tr(requestbody.toString()),
  }
}

// 请求拦截器
instance.interceptors.request.use(
  config => {
    const jwtToken = getToken()
    if (jwtToken) {
      addRequestHeaders(config, jwtToken)
    }
    return config
  },
  error => {
    // do something with request error
    console.log('请求错误:', error) // for debug
    return Promise.reject(error)
  }
)

// 相应拦截器
instance.interceptors.response.use(
  response => {
    const res = response.data

    if (res.code === 200) {
      return response.data
    } else {
      if(res.code === 401) {
        delToken()
        Message.error('登录信息已过期，请重新登录！')
        router.replace('/login')
      }
      return response.data
    }
  },
  error => {
    console.log('响应错误', error.response) // for debug

    if (error.response) {
      const { status } = error.response;
      if (status === 401 || status === 502) {
        Message.error('登录信息已过期，请重新登录！')
        delToken()
        router.replace('/login')
      } else if (status === 403) {
        Message.error(error.response.data.message || error.message)
        // router.replace('/403')
      } else if (status >= 404 && status < 422) {
        Message.error(error.response.data.message || error.message)
        // router.replace('/404')
      } else {
        Message.error(error.response.data.message || error.message)
      }
    } else {
      Message.error(error.message)
    }

    return Promise.reject(error)
  }
)

export default instance
